<?php

namespace App\Helper;

class Tree
{
    public static function buildTree(array $elements, $parentId = 0, $idKey = 'id', $parentKey = 'p_id', $childrenKey = 'children')
    {
        $tree = [];
        $references = [];

        // 初始化 references 数组，用于快速查找
        foreach ($elements as &$element) {
            $references[$element[$idKey]] = &$element;
        }

        // 构建树形结构
        foreach ($elements as &$element) {
            if ($element[$parentKey] == $parentId) {
                $tree[] = &$element;
            } else {
                if (isset($references[$element[$parentKey]])) {
                    $references[$element[$parentKey]][$childrenKey][] = &$element;
                }
            }
        }

        unset($element); // 解除引用

        return $tree;
    }
}
